# -*- coding: UTF-8 -*-

import socket, sys
import pygame, numpy
from PyQt5 import QtWidgets, QtCore, QtGui
from remote.ui_maindialog import Ui_MainWindow


# 主机地址和端口
host = '127.0.0.1'
port = 10219

# 服务器地址，初始化socket
ser_address = ('127.0.0.1', 10218)
cli_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
cli_socket.bind((host, port))


# 向服务器发送消息，并判断接收时是否超时，若超时则重发
while 1:
    cli_socket.sendto(bytes('startCam', encoding="utf8"), ser_address)
    try:
        message, address = cli_socket.recvfrom(65536)
        if message.decode() == 'startRcv':
            break
    except socket.timeout:
        print("timeout")
        continue

# 此句无用。。防止窗口初始化后等待数据
cli_socket.recvfrom(65536)

# 初始化视频窗口
pygame.init()
screen = pygame.display.set_mode((160, 120))
pygame.display.set_caption('Web Camera')
pygame.display.flip()

# 设置时间，可以用来控制帧率
clock = pygame.time.Clock()

def call_info(Ui_MainWindow):
    #主循环，显示视频信息
    while 1:
        try:
            data, address = cli_socket.recvfrom(65536 * 32)
        except socket.timeout:
            continue
        Ui_MainWindow.show_image(data)
        camshot = pygame.image.frombuffer(data, (160, 120), 'RGB')
        camshot = pygame.transform.scale(camshot, (160, 120))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                cli_socket.sendto(bytes('quitCam', encoding="utf8"), ser_address)
                cli_socket.close()
                pygame.quit()
                exit()
        screen.blit(camshot, (0, 0))
        pygame.display.update()
        clock.tick(20)

app = QtWidgets.QApplication(sys.argv)
window = Ui_MainWindow()
mainWindow = QtWidgets.QMainWindow()
mainWindow.setWindowFlags(QtCore.Qt.WindowCloseButtonHint)
window.setupUi(mainWindow)
mainWindow.show()
call_info(window)
sys.exit(app.exec_())








